package org.mifos.boss.persistence;

import java.util.List;
import java.util.Map;

import javax.persistence.PersistenceException;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * This class forms the base for all DAOs used in BOSS. Database connections etc, which is
 * used across BOSS can be initiated/referenced here. 
 */

public class BaseBossPersistence {
	@Autowired
	protected SessionFactory sessionFactory;
	
	protected static Logger logger = Logger.getLogger(BaseBossPersistence.class);
	
	public Session getCurrentHibernateSession(){
		if(sessionFactory != null){
			return sessionFactory.getCurrentSession();
		}
		return null;
	}
	
	public void save(Object object){
		getSession().save(object);
	}
	
	public void executeQuery(){
		
	}
	
	
    public List executeNamedQuery(final String queryName, final Map<String, ?> queryParameters) throws PersistenceException {
        try {
            Query query = createdNamedQuery(queryName);
            query.setProperties(queryParameters);
            return query.list();
        } catch (Exception e) {
            throw new PersistenceException(e);
        }
    }
    
    public Query createdNamedQuery(final String queryName) {
        Query query = getSession().getNamedQuery(queryName);
        logger.debug("The query object for the query with the name  " + queryName + " has been obtained");
        return query;
    }
    
    public Session getSession() {
        return getCurrentHibernateSession();
    }

}
